<?php


namespace plugin\coupon\app\admin\logic;


use app\common\logic\BaseLogic;
use plugin\coupon\app\model\Coupon;
use plugin\coupon\app\model\CouponReceiveLog;
use support\exception\BadException;
use support\utils\Decimal;
use support\utils\Time;

class CouponLogic extends BaseLogic
{
    /**
     * @var CouponReceiveLog
     */
    protected CouponReceiveLog $couponReceiveLogModel;

    public function __construct()
    {
        $this->model = new Coupon();
        $this->couponReceiveLogModel = new CouponReceiveLog();
    }

    public function getCanUse($uid, $goodsList)
    {
        $list = $this->couponReceiveLogModel->where([
            'user_id' => $uid,
            'status' => CouponReceiveLog::STATUS_NO_USED,
        ])
            ->with([
                'coupon',
                'coupongoods',
            ])
            ->select()->toArray();
        $new = [];
        foreach ($list as $key => $value) {
            if ($value['end_time'] <= Time::now() && $value['start_time'] >= Time::now()) {
                unset($list[$key]);
                continue;
            }
            if (!$value['coupon']) {
                unset($list[$key]);
                continue;
            }
            if (!$this->checkCouponThreshold($goodsList, $value)) {
                continue;
            }
            $new[] = [
                'id' => $value['id'],
                'name' => $value['coupon']['name'],
                'type' => $value['coupon']['type'],
                'discount' => $value['coupon']['discount'],
                'max_discount_amount' => $value['coupon']['max_discount_amount'],
                'amount' => $value['coupon']['amount'],
                'threshold_amount' => $value['coupon']['threshold_amount'],
                'is_threshold' => $value['coupon']['is_threshold'],
                'end_time' => $value['end_time'],
            ];
        }
        return $new;
    }

    /**
     * 校验卡券的门槛金额
     * @param $goodsList
     * @param $item
     * @return bool
     */
    public function checkCouponThreshold($goodsList, $item)
    {
        $calMoneyDecimal = Decimal::newDecimal(0);
        $coupon = $item['coupon'];
        if ($coupon['join_goods'] == Coupon::JOIN_GOODS_DESIGNATED) {
            $couponGoods = array_column($item['coupongoods'], 'goods_id');
            foreach ($goodsList as $goods) {
                if (in_array($goods['goods_id'], $couponGoods)) {
                    $calMoneyDecimal->add($goods['total_price']);
                }
            }
        }
        if ($coupon['join_goods'] == Coupon::JOIN_GOODS_ALL) {
            foreach ($goodsList as $goods) {
                $brandTrue = empty($coupon['goods_brand_ids']) ? true : in_array($goods['brand_id'], $coupon['goods_brand_ids']);
                $cateTrue = empty($coupon['goods_category_ids']) ? true : array_intersect($goods['cate_ids'], $coupon['goods_category_ids']);
                $tagTrue = empty($coupon['goods_tag_ids']) ? true : array_intersect($goods['tag_ids'], $coupon['goods_tag_ids']);
                if ($brandTrue && $cateTrue && $tagTrue) {
                    $calMoneyDecimal->add($goods['total_price']);
                }
            }
        }

        if ($coupon['is_threshold'] == 1
            && $calMoneyDecimal->getValue() < $coupon['threshold_amount']) {
            return false;
        }
        return true;
    }

    /**
     * 收集满足卡券的商品 以及对应的金额
     * @param $goodsList
     * @param $item
     * @return array
     */
    public function collectCouponGoods($goodsList, $item)
    {
        $collectGoods = [];
        $calMoneyDecimal = Decimal::newDecimal(0);
        $coupon = $item['coupon'];
        if ($coupon['join_goods'] == Coupon::JOIN_GOODS_DESIGNATED) {
            $couponGoods = array_column($item['coupongoods'], 'goods_id');
            foreach ($goodsList as $goods) {
                if (in_array($goods['goods_id'], $couponGoods)) {
                    $calMoneyDecimal->add($goods['total_price']);
                    $collectGoods[$goods['goods_id']] = $goods['total_price'];
                }
            }
        }
        if ($coupon['join_goods'] == Coupon::JOIN_GOODS_ALL) {
            foreach ($goodsList as $goods) {
                $brandTrue = empty($coupon['goods_brand_ids']) ? true : in_array($goods['brand_id'], $coupon['goods_brand_ids']);
                $cateTrue = empty($coupon['goods_category_ids']) ? true : array_intersect($goods['cate_ids'], $coupon['goods_category_ids']);
                $tagTrue = empty($coupon['goods_tag_ids']) ? true : array_intersect($goods['tag_ids'], $coupon['goods_tag_ids']);
                if ($brandTrue && $cateTrue && $tagTrue) {
                    $calMoneyDecimal->add($goods['total_price']);
                    $collectGoods[$goods['goods_id']] = $goods['total_price'];
                }
            }
        }

        if ($coupon['is_threshold'] == 1
            && $calMoneyDecimal->getValue() < $coupon['threshold_amount']) {
            throw new BadException("优惠券使用异常");
        }
        return [
            'collectGoods' => $collectGoods,
            'totalPrice' => $calMoneyDecimal->getValue()
        ];
    }

}